import type { Ref, WritableComputedRef } from 'vue'

export default function useDragger(
  blocks: Ref<{ container: {}; blocks: Array<any> }>,
  selector: string
) {
  let currentComp: any = null
  function dragStart(param: any, comp: any) {
    currentComp = comp
    const editorCanvasContainer = document.querySelector(selector)
    editorCanvasContainer?.addEventListener('dragenter', handleDragEnter)
    editorCanvasContainer?.addEventListener('dragover', handleDragOver)
    editorCanvasContainer?.addEventListener('dragleave', handleDragLeave)
    editorCanvasContainer?.addEventListener('drop', handleDrop)
  }
  function drawEnd(param: any) {
    const editorCanvasContainer = document.querySelector(selector)
    editorCanvasContainer?.removeEventListener('dragenter', handleDragEnter)
    editorCanvasContainer?.removeEventListener('dragover', handleDragOver)
    editorCanvasContainer?.removeEventListener('dragleave', handleDragLeave)
    editorCanvasContainer?.removeEventListener('drop', handleDrop)
  }
  function handleDragEnter(param: any) {
    param.preventDefault()
    param.dataTransfer.dropEffect = 'copy'
  }
  function handleDragOver(param: any) {
    param.preventDefault()
  }
  function handleDragLeave(param: any) {}
  function handleDrop(param: any) {
    param.dataTransfer.effectAllowed = 'all'
    const className = 'absolute'
    const style = {
      left: param.offsetX,
      top: param.offsetY
    }
    const { name } = currentComp
    blocks.value.blocks.push({ key: name, class: className, style, alignCenter: true })
    currentComp = null
  }
  return {
    dragStart,
    drawEnd
  }
}
